// index.js
Page({
  data: {
    totalCount: 0,
    usedCount: 0,
    remainingCount: 0,
    // agentCodeUrl: 'images/dd.png',
    agentCodeUrl: '',
    agentCode: '',
    agentName: '',
    deviceId: '',
    userInfo:{},
    merchant:{},
  },

  onLoad() {
    this.getTitle();
    this.deviceInfo();
    // this.getUserInfo();

  },

  getUserInfo(){
    tt.getUserProfile({
      success(res) {
        console.log("getUserProfile 调用成功：", res.userInfo);
      },
      fail(res) {
        console.log("getUserProfile 调用失败", res);
      },
    });
  },

  getQRcode(){
    tt.request({
      url: 'https://dapp.jiantech.cn/api/dyDevices/getQRcode',
      method: 'POST',
      data: {imei,userId},
      success: (res) => {
        console.log(res);
        if (res.data.code === 200) {
          this.setData({
            usedCount: res.data.data.usedCount || 0,
            totalCount: res.data.data.totalCount,
            remainingCount: res.data.data.totalCount - res.data.data.usedCount
          });
        } else {
          this.setData({
            usedCount: 0,
            remainingCount: 0
          });
        }
      },
      fail: () => {
        tt.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  getTitle(){
    tt.request({
      // url: 'http://localhost:9002/systemConfig/title',
      url: 'https://dapp.jiantech.cn/api/systemConfig/title',
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.data.code === 200) {
          console.log(res.data);
          console.log("getTitle",res.data.data);
          this.setData({
            contentData:res.data.data
          });
        } else {
          this.setData({
            usedCount: 0,
            remainingCount: 0
          });
        }
      },
      fail: () => {
        tt.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  deviceInfo(){
    // 从缓存获取 deviceId
    const deviceIdFromStorage = tt.getStorageSync('deviceId');
    const userInfo = tt.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo: userInfo });
    }
    if (deviceIdFromStorage) {
      this.setData({ deviceId: deviceIdFromStorage });
      const imei = this.data.deviceId;
      const userId=this.data.userInfo.id
      if(imei){
        tt.request({
          url: 'https://dapp.jiantech.cn/api/dyDevices/deviceInfo',
          method: 'POST',
          data: {imei,userId},
          success: (res) => {
            console.log(res);
            if (res.data.code === 200) {
              this.setData({
                usedCount: res.data.data.usedCount || 0,
                totalCount: res.data.data.totalCount,
                remainingCount: res.data.data.totalCount - res.data.data.usedCount,
                merchant:res.data.data.merchant,
                agentCodeUrl: res.data.data.merchant.qmCode,
                agentCode: res.data.data.merchant.dyCode,
                agentName: res.data.data.merchant.dyName,
              });
            } else {
              this.setData({
                usedCount: 0,
                remainingCount: 0
              });
            }
          },
          fail: () => {
            tt.showToast({
              title: '网络错误',
              icon: 'none'
            });
          }
        });
      }
    }
  },


  handleStartDevice() {

    console.log("this.data:",this.data);
    if (this.data.remainingCount <= 0) {
      tt.showToast({ title: this.data.contentData.no_times, icon: 'none' })
      return;
    }

    // 触觉反馈
    tt.vibrateShort()
    
    // 按钮动画
    this.triggerBtnAnimation()

  },

  triggerBtnAnimation() {
    this.setData({ btnAnimating: true })
    setTimeout(() => {
      this.setData({ btnAnimating: false })
    }, 200)
  },

  // 修改后的保存二维码函数
  saveQRCode() {
    // 直接调用保存图片到相册的方法，会自动触发授权流程
    tt.saveImageToPhotosAlbum({
      // 这里假设你有一个图片的临时路径，需要替换为实际的路径
      filePath: 'your_image_temp_path', 
      success: () => {
        tt.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        tt.showModal({
          title: '保存失败',
          content: err.errMsg,
          confirmText: '去设置',
          success: (res) => {
            if (res.confirm) {
              tt.openSetting();
            }
          }
        });
      }
    });
  },

  // 实际保存操作
  doSaveImage() {
    tt.saveImageToPhotosAlbum({
      filePath: '/images/douyin-qr.png',
      success: () => {
        tt.showToast({ title: '保存成功' });
      },
      fail: (err) => {
        console.error('保存失败:', err);
        tt.showToast({ title: '保存失败，请重试' });
      }
    });
  },

  // 设备启动处理
  handleDeviceStart(e) {
    // 从 data 中获取 deviceId
    const imei = this.data.deviceId;
    const userId=this.data.userInfo.id

    console.log("this.data:",this.data);
    if (this.data.remainingCount <= 0) {
      tt.showToast({ title: this.data.contentData.no_times, icon: 'none' })
      return;
    }

    // 触觉反馈
    tt.vibrateShort()
    
    // 按钮动画
    this.triggerBtnAnimation()
    
    // 启动接口调用
    tt.request({
      url: 'https://dapp.jiantech.cn/api/dyDevices/startDevice',
      method: 'POST',
      data: {imei,userId},
      success: (res) => {
        console.log(res);
        if (res.data.code === 200) {
          console.log("this.data.contentData.startDevice_showToast:",this.data.contentData.startDevice_showToast);
          tt.showToast({
            title: this.data.contentData.startDevice_showToast,
            icon: 'success'
          });
          this.deviceInfo();
        } else {
          tt.showToast({
            title: res.data.desc,
            icon: 'fail'
          });
        }
      },
      fail: () => {
        tt.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
});
